package com.group.sliding.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group.sliding.context.UserContext;
import com.group.sliding.domain.po.Address;
import com.group.sliding.domain.query.AddressPageQuery;
import com.group.sliding.enums.DefaultFlag;
import com.group.sliding.mapper.AddressMapper;
import com.group.sliding.service.IAddressService;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {

    @Override
    public void updateIsDefault(Long id, Boolean isDefault) {
        // 将原来的默认地址都设为非默认地址
        UpdateWrapper<Address> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .eq(Address::getUserId, UserContext.getUser())
                .set(Address::getIsDefault, DefaultFlag.NOT_DEFAULT);
        update(updateWrapper);
        // 再设置当前的状态
        Address address = new Address();
        address.setId(id);
        address.setIsDefault(DefaultFlag.of(isDefault));
        updateById(address);
    }

    @Override
    public Page<Address> search(AddressPageQuery query) {
        return lambdaQuery()
                .eq(query.getId() != null, Address::getId, query.getId())
                .eq(query.getUserId() != null, Address::getUserId, query.getUserId())
                .page(query.toMpPage("user_id", false));
    }
}
